package edu.csl.study.shardingsphere.hint;

import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlMasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;


public class DataSourceHelper {

    volatile  static DataSource dataSource1 = null;
    volatile  static DataSource dataSource2 = null;
    volatile  static DataSource dataSource3 = null;
	static DataSource getDataSourceForShardingDatabases() throws IOException, SQLException {

       if(dataSource1 == null) {
           synchronized (DataSourceHelper.class) {
               if (dataSource1 == null) {
                   dataSource1 = YamlShardingDataSourceFactory.createDataSource(getFile("/hint/hint-databases.yaml"));
               }
           }
       }
       return dataSource1;
    }
	
	static DataSource getDataSourceForShardingDatabasesAndTables() throws IOException, SQLException {
        if(dataSource2 == null) {
            synchronized (DataSourceHelper.class) {
                if (dataSource2 == null) {
                    dataSource2 = YamlShardingDataSourceFactory.createDataSource(getFile("/hint/hint-databases-tables.yaml"));
                }
            }
        }
        return dataSource2;
    }
	
	static DataSource getDataSourceForMaster() throws IOException, SQLException {
        if(dataSource3 == null) {
            synchronized (DataSourceHelper.class) {
                if (dataSource3 == null) {
                    dataSource3 = YamlShardingDataSourceFactory.createDataSource(getFile("/hint/hint-master-only.yaml"));
                }
            }
        }
        return dataSource3;

    }
	
    private static File getFile(final String configFile) {
        return new File(Thread.currentThread().getClass().getResource(configFile).getFile());
    }
}
